package com.stillalive.blogsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stillalive.blogsystem.common.constant.Constants;
import com.stillalive.blogsystem.common.exception.BlogException;
import com.stillalive.blogsystem.common.util.BeanTransUtils;
import com.stillalive.blogsystem.common.util.JwtUtils;
import com.stillalive.blogsystem.common.util.SecurityUtil;
import com.stillalive.blogsystem.mapper.UserInfoMapper;
import com.stillalive.blogsystem.pojo.dataobject.BlogInfo;
import com.stillalive.blogsystem.pojo.dataobject.UserInfo;
import com.stillalive.blogsystem.pojo.request.UserLoginRequest;
import com.stillalive.blogsystem.pojo.request.UserRegisterRequest;
import com.stillalive.blogsystem.pojo.response.UserInfoResponse;
import com.stillalive.blogsystem.pojo.response.UserLoginResponse;
import com.stillalive.blogsystem.service.BlogService;
import com.stillalive.blogsystem.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource(name = "blogServiceImpl")
    private BlogService blogService;

    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName,userLoginRequest.getUserName())
                .eq(UserInfo::getDeleteFlag, Constants.UNDELETE_FLAG);
        // 查询数据库
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if(userInfo == null){
            throw new BlogException("用户不存在..");
        }
        if(!SecurityUtil.verify(userLoginRequest.getPassword(), userInfo.getPassword())){
            throw new BlogException("密码错误..");

        }
        // 密码正确
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userInfo.getId());
        map.put("userName", userInfo.getUserName());
        String token = JwtUtils.genToken(map);
        return new UserLoginResponse(userInfo.getId(), token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag, Constants.UNDELETE_FLAG)
                .eq(UserInfo::getId, userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return BeanTransUtils.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if(blogInfo == null || blogInfo.getUserId() <= 0){
            throw new BlogException("博客不存在..");
        }
        return getUserInfo(blogInfo.getUserId());
    }

    @Override
    public Boolean registerUser(UserRegisterRequest userRegisterRequest) {
        // 验证密码确认
        if (!userRegisterRequest.getPassword().equals(userRegisterRequest.getConfirmPassword())) {
            throw new BlogException("两次输入的密码不一致");
        }
        
        // 检查用户名是否已存在
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName, userRegisterRequest.getUserName())
                .eq(UserInfo::getDeleteFlag, Constants.UNDELETE_FLAG);
        UserInfo existingUser = userInfoMapper.selectOne(queryWrapper);
        if (existingUser != null) {
            throw new BlogException("用户名已存在");
        }
        
        // 创建新用户
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userRegisterRequest.getUserName());
        userInfo.setPassword(SecurityUtil.encrypt(userRegisterRequest.getPassword()));
        userInfo.setGithubUrl(userRegisterRequest.getGithubUrl());
        userInfo.setDeleteFlag(Constants.UNDELETE_FLAG);
        userInfo.setCreateTime(LocalDate.now());
        userInfo.setUpdateTime(LocalDate.now());
        
        int result = userInfoMapper.insert(userInfo);
        return result > 0;
    }
}
